package com.test45_JUC;

import org.junit.Test;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * TimeUtil工具类，枚举，简化时间的计算管理
 */
public class Demo01_TimeUnit {

    @Test
    public void test1() {
        {
            long hour = 1;
            // 小时转换为秒
            long second = TimeUnit.SECONDS.convert(hour, TimeUnit.HOURS);
            System.out.println("小时转秒数：" + second);
            // 小时转换为分钟
            long minute = TimeUnit.MINUTES.convert(hour, TimeUnit.HOURS);
            System.out.println("小时转分钟：" + minute);
        }
        {
            int day = 1;
            // 天转换为秒
            long second = TimeUnit.SECONDS.convert(day, TimeUnit.DAYS);
            System.out.println("一天的秒数：" + second);
        }
    }

    /**
     * java.time.Daration，时间间隔类
     */
    @Test
    public void test2() {
        // 2小时+2小时
        Duration duration = Duration.ofHours(2).plusHours(2);
        System.out.println("时间间隔：" + duration);
        // long second = TimeUnit.SECONDS.convert(duration);
        long second = duration.getSeconds();
        System.out.println("间隔的秒数：" + second);
    }

    /**
     * 计算180天之后的日期
     */
    @Test
    public void test3() {
        long current = System.currentTimeMillis();
        long after = current + TimeUnit.MILLISECONDS.convert(180, TimeUnit.DAYS);
        System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(new Date(after)));
    }

    /**
     * 实现线程的休眠操作
     */
    @Test
    public void test4() {
        for (int x = 0; x < 100; x++) {
            try {
                TimeUnit.SECONDS.sleep(2);  // 根据秒来休眠
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("【x = " + x + "】沐言科技：www.yootk.com");
        }
    }
}
